package com.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.domain.Code;
import com.domain.Drug;
import com.domain.Result;
import com.service.IDrugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-03-07
 */
@RestController
@RequestMapping("/drug")
public class DrugController {

    @Autowired
    private IDrugService iDrugService;

    @GetMapping
    public Result getAll(){
        List<Drug> list = iDrugService.list();
        if(list!=null){
            return new Result(list,"查询成功", Code.GET_OK);
        }else
        {
            return new Result(list,"查询失败", Code.GET_ERR);
        }

    }
//
//    @GetMapping("/{drugId}")
//    public  Result getById(@PathVariable Integer drugId){
//        Drug drug = iDrugService.getById(drugId);
//        if(drug!=null){
//            return new Result(drug,"查询成功", Code.GET_OK);
//        }else
//        {
//            return new Result(drug,"查询失败", Code.GET_ERR);
//        }
//    }

    //模糊搜索
    @GetMapping("/{drugName}")
    public  Result getByName(@PathVariable String drugName){
        QueryWrapper<Drug> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("drug_name",drugName);
        List<Drug> list = iDrugService.list(queryWrapper);
        if(list.isEmpty()){
            return new Result("查询失败", Code.GET_ERR);
        }else
        {
            return new Result(list,"查询成功", Code.GET_OK);
        }
    }

    @PostMapping
    public Result add(@RequestBody Drug drug){
        boolean flag = iDrugService.save(drug);
        if(flag==true){
            return new Result("添加成功", Code.SAVE_OK);
        }else
        {
            return new Result("添加失败", Code.SAVE_ERR);
        }
    }

    @DeleteMapping("/{drugId}")
    public Result deleteById(@PathVariable Integer drugId){
        boolean flag = iDrugService.removeById(drugId);
        if(flag==true){
            return new Result("删除成功", Code.DELETE_OK);
        }else
        {
            return new Result("删除失败", Code.DELETE_ERR);
        }
    }

    @PutMapping
    public Result update(@RequestBody Drug drug){
        boolean flag = iDrugService.updateById(drug);
        if(flag==true){
            return new Result("修改成功", Code.UPDATE_OK);
        }else
        {
            return new Result("修改失败", Code.UPDATE_ERR);
        }
    }

    @GetMapping({"/{currentPage}/{pageSize}"})
    public Result selectByPage(@PathVariable Integer currentPage,@PathVariable Integer pageSize){
        IPage<Drug> page=new Page(currentPage,pageSize);
        iDrugService.page(page);
        return new Result(page.getRecords(),"查询成功", (int) page.getTotal());
    }
}

